  //
//  Utilization.m
//  lc
//
//  Created by Henry Pang on 2/23/14.
//  Copyright (c) 2014 Sita Tech. All rights reserved.
//

#import "Utilization.h"
#import "LKDBHelper.h"
static LKDBHelper* db = nil;

@implementation Utilization

#pragma mark - identifier dictionary

//+ (NSString*) getViewControllerIdentifier:(LCPaneViewControllerType) paneViewControllerType{
//    return [Constants paneViewControllerIdentifiers][@(paneViewControllerType)];
//}

//获取用户头像路径
+ (NSString*) getDocPathAndAccountid
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *accountId = [[NSUserDefaults standardUserDefaults] valueForKey:@"pallaAccountId"];
    accountId=[accountId stringByAppendingString:@"userImage"];
    NSString *apath = [NSString stringWithFormat:@"%@/%@",path,accountId];
    return apath;
}

//For LC in
+ (NSString*) getSubViewControllerIdentifier:(LCSubPaneViewControllerType) paneViewControllerType{
    return [Constants SubPaneViewControllerIdentifiers][@(paneViewControllerType)];
}

+ (NSString*) getPlistDictionaryIdentifier:(LCPlistDictionaryType) plistDictionaryType{
    return [Constants plistDictionaryIdentifiers][@(plistDictionaryType)];
}

+ (NSString*) getFolerDirectoryIdentifier:(LCFolerDirectoryType) folerDirectoryType{
    return [Constants folerDirectoryIdentifiers][@(folerDirectoryType)];
}

#pragma mark - for View Controller
+(AppDelegate *)appDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}


#pragma mark - for plist handles

+ (id) dictionaryArrayFromPlist:(LCSandboxPathType) sandboxPathType folder:(NSString *) folder plistDictionaryType:(LCPlistDictionaryType) plistDictionaryType {
    
    NSString *pathWithFolderName = [NSString alloc];
    pathWithFolderName = [self sandBoxPath:LCSandboxPathTypeLibrary];
    pathWithFolderName = [pathWithFolderName stringByAppendingString:folder];
    pathWithFolderName = [pathWithFolderName stringByAppendingString:[self getPlistDictionaryIdentifier:LCPlistDictionaryTypeUserProfile]];
    pathWithFolderName = [pathWithFolderName stringByAppendingString:@".plist"];
    
    return [NSArray arrayWithContentsOfFile:pathWithFolderName];
    
}

+ (NSString *)sandBoxPath:(LCSandboxPathType) sandboxPathType {
    
    NSString *path = [NSString alloc];
    
    switch (sandboxPathType) {
        case LCSandboxPathTypeHome:
            path = NSHomeDirectory();
            break;
        case LCSandboxPathTypeDocument:{
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            path = [paths objectAtIndex:0];
            break;
        }
        case LCSandboxPathTypeLibrary:{
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
            path = [paths objectAtIndex:0];
            break;
        }
        case LCSandboxPathTypeCache:{
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            path = [paths objectAtIndex:0];
            break;
        }
        case LCSandboxPathTypeTemp:{
            path = NSTemporaryDirectory();
            break;
        }
        default:
            break;
    }
    
    return path;
}

+ (id)getDictionaryArrayByPlistType:(LCPlistDictionaryType) plistDictionaryType{
    NSString *plistDictionaryIdendifier = [self getPlistDictionaryIdentifier:plistDictionaryType];
    NSString *path = [[NSBundle mainBundle] pathForResource:plistDictionaryIdendifier ofType:@"plist"];
    return [NSArray arrayWithContentsOfFile:path];
}



#pragma mark - for Database

+ (BOOL) isDBEncrypted {
    return [[NSUserDefaults standardUserDefaults] boolForKey: @"IsDBEncrypted"];
}

+ (void) setDBEncrypted:(BOOL) isDBEncrypted {
    [[NSUserDefaults standardUserDefaults] setBool:isDBEncrypted forKey:@"IsDBEncrypted"];
}

+ (NSString *) getDBEncryptKey {
    return [[NSUserDefaults standardUserDefaults] stringForKey: @"DBEncryptKey"];
}

+ (void) setDBEncryptKey:(NSString *) encryptKey {
    [[NSUserDefaults standardUserDefaults] setObject:encryptKey forKey:@"DBEncryptKey"];
}

// Global LKDBHelper
+ (LKDBHelper *) getUsingLKDBHelper {
    //static dispatch_once_t onceToken;
    //dispatch_once(&onceToken, ^{
        //db = [[LKDBHelper alloc]initWithDBPath:[self getDBPathWithName]];
////        db = [[LKDBHelper alloc]initWithDBPath:[self getDBPathWithName] isDbEncrypted:[self isDBEncrypted]];
    //});
    
    @synchronized(self) {
        if (db == nil) {
            db = [[LKDBHelper alloc] initWithDBPath:[self getDBPathWithName]];
        }
    }
    return db;
}

+ (void)destroyLKDBHelper{
    if (db != nil)
    {
        db = nil;
    }
}

// Global DB path
+ (NSString *) getDBPathWithName {
    NSString *accountId = [[NSUserDefaults standardUserDefaults] objectForKey:@"pallaAccountId"];
    NSMutableString * dbName = [NSMutableString stringWithString:accountId];
    if ([self isDBEncrypted]) {
        [dbName appendString: @"-release"];
    }
    [dbName appendString: @".sqlite"];
    return [[Utilization sandBoxPath: LCSandboxPathTypeDocument] stringByAppendingPathComponent:dbName];
}

// LKDBHelper for creation
//+ (LKDBHelper *) getUsingLKDBHelperForUnencrypted {
    //static LKDBHelper* db;
    //static dispatch_once_t onceToken;
    //dispatch_once(&onceToken, ^{
        //db = [[LKDBHelper alloc]initWithDBPath:[self getDBPathWithNameForUnencrypted]];
////        db = [[LKDBHelper alloc]initWithDBPath:[self getDBPathWithNameForUnencrypted] isDbEncrypted:NO];
    //});
    
    //return db;
//}

// DB path for creation
+ (NSString *) getDBPathWithNameForUnencrypted {
    NSString *accountId = [[NSUserDefaults standardUserDefaults] objectForKey:@"pallaAccountId"];

    NSMutableString * dbName = [NSMutableString stringWithString:accountId];
    //@"lcdata"];
    // CFBundleVersion is for build, CFBundleShortVersionString is for publish
    //[dbName appendString: [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [dbName appendString: @".sqlite"];
    return [[Utilization sandBoxPath: LCSandboxPathTypeDocument] stringByAppendingPathComponent:dbName];
}

#pragma mark - for random

+ (NSInteger) random_integer:(NSInteger)maxValue {
    return arc4random() % maxValue;
}

+ (NSString*) random_char {
    NSMutableString *charString = [NSMutableString stringWithString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890+-=_/&%#*"];
    charString = [NSMutableString stringWithString:[charString substringFromIndex:[self random_integer:71]]];
    charString = [NSMutableString stringWithString:[charString substringToIndex:1]];
    return charString;
}

+ (NSString *) random_string:(NSInteger) length {
    NSMutableString *rdStr = [[NSMutableString alloc] init];
    for (NSInteger i = 0; i<length; i++) {
        [rdStr appendString:[NSString stringWithString:[self random_char]]];
    }
   // NSLog(@"random_string in Utilization:%@", rdStr);
    return rdStr;
}


+(NSString*)formatUserDataForUpload:(NSDictionary*) userData{
    
    NSError *error = nil;
    
    //Serialize the JSON data
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] > 0 && error == nil) {
        //Create a string from the JSON Data
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

        return jsonString;
    }
    else if ([jsonData length] == 0 && error == nil){
       // NSLog(@"No data was returned after the serialization");
    }
    else if (error != nil){
       // NSLog(@"An error happened = %@",error);
    }
    return nil;
}

//+ (UIImage *)createImageWithColor:(UIColor *)color
//{
//    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
//    UIGraphicsBeginImageContext(rect.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetFillColorWithColor(context, [color CGColor]);
//    CGContextFillRect(context, rect);
//    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    
//    return theImage;
//}
//
//+ (UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
//{
//    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
//    
//    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
//    
//    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    return scaledImage;   //返回的就是已经改变的图片
//}

@end
